package com.nowcoder.community.controller.advice;

import com.nowcoder.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

// 只扫描Controller，对Controller进行异常处理
// @ControllerAdvice(annotations = {Controller.class})
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler(Exception.class)
    public void handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("服务器发生异常：" + e.getMessage());
        // e.getStackTrace()得到一个数组
        for (StackTraceElement element : e.getStackTrace()) {
            logger.error(element.toString());
        }

        // 获取请求头中的请求方式
        String xRequestedWith = request.getHeader("x-requested-with");
        // 如果是异步请求
        if ("XMLHttpRequest".equals(xRequestedWith)) {
            // 返回json字符串，浏览器会自动转换
            // response.setContentType("application/json");

            // 返回一个普通文本，前端使用js自己转换
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtil.getJSONString(1, "服务器发生异常！"));
        } else {
            response.sendRedirect(request.getContextPath() + "/error");
        }
    }
}
